package com.net.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @ClassName NettyServer
 * @Description TODO
 * @Author zhuchen216628
 * @Date 2018/9/28 10:44
 * @Version 1.0
 **/
@Component
public class NettyServer {

    /**
     * 服务端监听的端口地址
     */
    private static final int portNumber = 7878;

    @Autowired
    private NettyServerInitializer nettyServerInitializer;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    public NettyServer(){
        System.out.println(111);
    }

    @PostConstruct
    public void init(){
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(nettyServerInitializer);

            // 服务器绑定端口监听
            ChannelFuture f = b.bind(portNumber).syncUninterruptibly();
            // 监听服务器关闭监听
//            f.channel().closeFuture().sync();

            // 可以简写为
            /* b.bind(portNumber).sync().channel().closeFuture().sync(); */
            System.out.println("1111111111111111111");
        } catch (Exception e){
            e.printStackTrace();
        } finally {
//            bossGroup.shutdownGracefully();
//            workerGroup.shutdownGracefully();
        }
    }

    public void shutdown() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
